using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using System.IO;
using DBDataContext.Model;

namespace AiyoriAoshi
{
    public partial class ContentPage : PhoneApplicationPage
    {
        // list of file name in folder
        string[] listFileNames;
        int index = 0;
        int chapterId = 0;
        byte[] data;
        string path = "";
        string searchPattern = "";
        double imgWidth = 480;
        double imgHeight = 800;


        double initialScale;
        bool isPinching;
        Chapter chapter;
        public ContentPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs args)
        {
            // Link: "/ContentPage.xaml?chapterId={0}"
            IDictionary<string, string> parameters = NavigationContext.QueryString;

            try
            {
                chapterId = int.Parse(parameters["chapterId"]);
                
            }
            catch (Exception ex)
            {
                index = 0;
                MessageBox.Show("Can't view this chapter. Error: " + ex.Message);
                string strUri = String.Format("/ChaptersPage.xaml");
                NavigationService.Navigate(new Uri(strUri, UriKind.Relative));
                return;
            }

            chapter = App.ViewModel.GetChapterByChapterId(chapterId);
            index = chapter.CurrentIndex;
            path = String.Format("Shared/Download/{0}/{1}/", chapter.MangaId, chapter.ChapterId);
            searchPattern = path + "*";

            try
            {
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    listFileNames = isf.GetFileNames(searchPattern);
                }
                SetSourceForImage();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Gặp lỗi khi chuyển trang: " + ex.Message);
            }

            isPinching = false;
        }

        private void SetSourceForImage()
        {
            try
            {
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (IsolatedStorageFileStream isfs = isf.OpenFile(path + listFileNames[index], FileMode.Open, FileAccess.Read))
                    {
                        // Allocate an array large enough for the entire file
                        data = new byte[isfs.Length];
                        
                        // Read the entire file and then close it
                        isfs.Read(data, 0, data.Length);
                        isfs.Dispose();
                        isfs.Close();



                        // Create memory stream and bitmap
                        MemoryStream ms = new MemoryStream(data);
                        
                        BitmapImage bi = new BitmapImage();

                        // Set bitmap source to memory stream
                        bi.SetSource(ms);

                        img.Height = imgHeight;
                        img.Width = imgWidth;

                        // Assign the bitmap image to the image’s source
                        img.Source = bi;
                    }
                    isf.Dispose();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error when see this image: " + ex.Message);
                //string strUri = String.Format("/ChaptersPage.xaml");
                string strUri = String.Format("/ChaptersPage.xaml");
                NavigationService.Navigate(new Uri(strUri, UriKind.Relative));
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            try
            {
                App.ViewModel.UpdateCurrentIndexByChapterID(chapterId, index);
                base.OnNavigatedFrom(e);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void MoveToNextPage()
        {
            index++;

            if (index < listFileNames.Count())
            {
                SetSourceForImage();
            }
            else
            {
                index = listFileNames.Count() - 1;
            }
        }

        private void MoveToPreviousPage()
        {
            index--;
            if (index >= 0)
            {
                SetSourceForImage();
            }
            else
            {
                index = 0;
            }
        }

        private void gl_DragCompleted(object sender, DragCompletedGestureEventArgs e)
        {
            if (isPinching == false)
            {
                if ((App.Current.RootVisual as PhoneApplicationFrame).Orientation == PageOrientation.PortraitUp)
                {
                    //var position  = e.GetPosition(;
                    if (e.HorizontalChange > 0)
                    {
                        //var transform = (CompositeTransform)this.img.RenderTransform;
                        //transform.TranslateX = ImagePosition.X;
                        //transform.TranslateY = ImagePosition.Y;
                        MoveToPreviousPage();
                    }

                    if (e.HorizontalChange < 0)
                    {
                        MoveToNextPage();
                    }


                }
                else if ((App.Current.RootVisual as PhoneApplicationFrame).Orientation == PageOrientation.Landscape)
                {

                }
            }
            else
            {
                //transform.TranslateX += e.HorizontalChange;
                //transform.TranslateY += e.VerticalChange;
            }
        }

        private void OnTap(object sender, GestureEventArgs e)
        {
            transform.TranslateX = transform.TranslateY = 0;
        }

        private void OnDoubleTap(object sender, GestureEventArgs e)
        {
            transform.ScaleX = transform.ScaleY = 1;
            isPinching = false;
        }

        private void OnHold(object sender, GestureEventArgs e)
        {
            transform.TranslateX = transform.TranslateY = 0;
            transform.ScaleX = transform.ScaleY = 1;
            transform.Rotation = 0;
        }

        private void OnDragStarted(object sender, DragStartedGestureEventArgs e)
        {
            //border.Background = greenBrush;
        }

        private void OnDragDelta(object sender, DragDeltaGestureEventArgs e)
        {
            if (isPinching == true)
            {
                transform.TranslateX += e.HorizontalChange;
                transform.TranslateY += e.VerticalChange;
            }
        }

        private void OnDragCompleted(object sender, DragCompletedGestureEventArgs e)
        {
            //border.Background = normalBrush;
        }

        private void OnPinchStarted(object sender, PinchStartedGestureEventArgs e)
        {
            isPinching = true;

            initialScale = transform.ScaleX;
        }

        private void OnPinchDelta(object sender, PinchGestureEventArgs e)
        {
            //transform.Rotation = initialAngle + e.TotalAngleDelta;
            if ( e.DistanceRatio > 1D)
            {
                transform.ScaleX = transform.ScaleY = initialScale * e.DistanceRatio;
            }
            //else
            //{
            //    transform.ScaleX = transform.ScaleY = initialScale;
            //}

            //radioScale = e.DistanceRatio;
        }

        private void OnPinchCompleted(object sender, PinchGestureEventArgs e)
        {
            //border.Background = normalBrush;
            //MessageBox.Show(radioScale.ToString());
        }

        private void OnFlick(object sender, FlickGestureEventArgs e)
        {

        }            //flickData.Text = string.Format("{0} Flick: Angle {1} Velocity {2},{3}",
        //    e.Direction, Math.Round(e.Angle), e.HorizontalVelocity, e.VerticalVelocity);


        #region AppBar
        private void settingPageButton_Click(object sender, EventArgs e)
        {
            string strUri = String.Format("/SettingPage.xaml");
            NavigationService.Navigate(new Uri(strUri, UriKind.Relative));
        }

        private void homePageButton_Click(object sender, EventArgs e)
        {
            string strUri = String.Format("/ChaptersPage.xaml");
            NavigationService.Navigate(new Uri(strUri, UriKind.Relative));
        }

        private void downloadPageButton_Click(object sender, EventArgs e)
        {
            string strUri = String.Format("/DownloadPage.xaml");
            NavigationService.Navigate(new Uri(strUri, UriKind.Relative));
        }

        private void aboutPageButton_Click(object sender, EventArgs e)
        {
            string strUri = String.Format("/AboutPage.xaml");
            NavigationService.Navigate(new Uri(strUri, UriKind.Relative));
        }
        #endregion
    }
}